package cn.com.cennavi.test;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.opengis.feature.simple.SimpleFeature;

import com.vividsolutions.jts.geom.GeometryFactory;

/**
 * 
 * @ClassName: ReadSHPFile
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author buf
 * @date 2017年2月10日 上午9:36:49
 *
 */
public class ReadSHPFile {
	/**
	 * 读取shape文件.
	 * 
	 * @param shapePath
	 *            shapefile路径文件
	 * @return SimpleFeatureSource
	 * @throws Exception
	 *             读取异常
	 */
	public static SimpleFeatureSource read(String shapePath) throws Exception {
		try {
			
			GeometryFactory geometryFactory = new GeometryFactory();
			File file = new File(shapePath);
			Map<String, Object> connect = new HashMap<String, Object>();
			connect.put("url", file.toURI().toURL());
			DataStore dataStore = DataStoreFinder.getDataStore(connect);
			String[] typeNames = dataStore.getTypeNames();
			String typeName = typeNames[0];
			SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
			return featureSource;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static HashMap<Long, Long> getReplaceNodeKV(String inNodeShapePath) throws Exception {

		// 处理临界点号，把在不同网格，坐标相同，编号不同的归一
		HashMap<Long, Long> ajNodeKV = new HashMap<Long, Long>();

		// 定义节点集合
		FeatureCollection ncollection = null;
		Iterator nIterator = null;

		// 读取节点表，获取邻接点信息
		SimpleFeatureSource featureSource = read(inNodeShapePath);
		if (featureSource == null) {
			return ajNodeKV;
		}
		ncollection = featureSource.getFeatures();
		nIterator = ncollection.iterator();

		while (nIterator.hasNext()) {
			SimpleFeature feature = (SimpleFeature) nIterator.next();
			System.out.println(feature.getName());
			// 获取节点ID
			int id = Integer.parseInt((String) feature.getAttribute(feature.getName()));
			System.out.println(id);
		}

		featureSource.getDataStore().dispose();
		return ajNodeKV;
	}

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		getReplaceNodeKV("D:\\mapinfoData\\xiamen\\xiamen_Shape\\xiamenjiaotongxiaoqu.SHP");
	}

}
